package com.example.emergencyattempt01.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import com.example.emergencyattempt01.R;
import com.example.emergencyattempt01.activity.administrator_activity.Update_User_Activity;
import com.example.emergencyattempt01.activity.utils.NetWorkUtils;
import com.example.emergencyattempt01.activity.utils.ServerMessage;
import de.hdodenhof.circleimageview.CircleImageView;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.Map;


public class Person_ListView_Adapter extends BaseAdapter {
    List<Map<String,Object>> itemList;
    Context context;
    ViewHolder viewHolder;

    public Person_ListView_Adapter(List<Map<String,Object>> itemList, Context context) {
        this.itemList = itemList;
        this.context = context;
    }
class ViewHolder
{
  CircleImageView profile;
  TextView userNameField;
  TextView uidField;
  TextView instituteField;
  TextView ownBookS;
  TextView identityField;

  Button update_info_btn;
  ImageView deleteUser;

}


Handler handler=new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
          switch (msg.what)
          {
              case DELETE_SUCCESS:
                  Toast.makeText(context,"已删除",Toast.LENGTH_SHORT).show();
                  int position=(int)msg.obj;
                  itemList.remove(position);
                  notifyDataSetChanged();
                  break;
              case DELETE_FAIL:
                  Toast.makeText(context,"删除失败",Toast.LENGTH_SHORT).show();
                  notifyDataSetChanged();
                  break;
              case DELETE_DENY:
                  Toast.makeText(context,"无法删除，本用户当前有在借书目",Toast.LENGTH_SHORT).show();
                  break;
          }
        }
    };
    final int DELETE_SUCCESS=0x012;
    final int DELETE_FAIL=0x013;
    final int DELETE_DENY=0x014;

    @Override
    public int getCount() {
        return itemList.size();
    }

    @Override
    public Object getItem(int position) {
       return  itemList.get(position);
    }

    @Override
    public long getItemId(int position) {
       return (long)itemList.get(position).get("uid");

    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final LayoutInflater inflater=LayoutInflater.from(context);
        if(convertView==null)
        {
            viewHolder=new ViewHolder();
            convertView=inflater.inflate(R.layout.person_info_item,null);
            viewHolder.deleteUser=convertView.findViewById(R.id.person_delete);
            viewHolder.identityField=convertView.findViewById(R.id.person_info_identity);
            viewHolder.instituteField=convertView.findViewById(R.id.person_info_institute);
            viewHolder.profile=convertView.findViewById(R.id.person_info_profile);
            viewHolder.ownBookS=convertView.findViewById(R.id.person_info_ownBooks);
            viewHolder.uidField=convertView.findViewById(R.id.person_info_uid);
            viewHolder.userNameField=convertView.findViewById(R.id.person_info_name);
            viewHolder.update_info_btn=convertView.findViewById(R.id.person_info_update);

            convertView.setTag(viewHolder);
        }
        else
        {
          viewHolder=(ViewHolder) convertView.getTag();
        }
        // 对这些控件设值


            viewHolder.instituteField.setText((String)itemList.get(position).get("institute"));
            viewHolder.userNameField.setText((String)itemList.get(position).get("userName"));
            int ownBooks=(int)itemList.get(position).get("ownBooks");
            if(ownBooks<=5)
               viewHolder.ownBookS.setText(ownBooks+"本");
            else
               viewHolder.ownBookS.setText("5本");
            String userType=(String) itemList.get(position).get("userType");
            if(userType.equals("学生"))
            {
                viewHolder.profile.setImageResource(R.drawable.ic_student_profile);
            }
            else if (userType.equals("管理员"))
            {
                viewHolder.profile.setImageResource(R.drawable.ic_administrator);
            }
            viewHolder.uidField.setText("uid:"+(long)itemList.get(position).get("uid"));
            viewHolder.identityField.setText((String)itemList.get(position).get("identity"));

            /** 需要增加两个监听，一个跳到修改页
             * 一个弹出确认框，问你删不删这个用户
             * 2020.12.19 20:18 董延涛
             */
            viewHolder.update_info_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(context, Update_User_Activity.class);
                    intent.putExtra("uid",(long)itemList.get(position).get("uid"));
                    intent.putExtra("userName",(String)itemList.get(position).get("userName"));
                    intent.putExtra("identity",(String)itemList.get(position).get("identity"));
                    intent.putExtra("institute",(String)itemList.get(position).get("institute"));
                    intent.putExtra("password",(String)itemList.get(position).get("password"));

                    context.startActivity(intent);
                }
            });

            final View temp=convertView;
            viewHolder.deleteUser.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder=new AlertDialog.Builder(temp.getContext());
                    builder.setMessage("确定要删除这个用户吗？");
                    builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 执行删除操作,打包当前uid，发送至服务器
                            new Thread(){
                                @Override
                                public void run() {
                                    try
                                    {
                                        JSONObject object=new JSONObject();
                                        object.put("uid",getItemId(position));
                                        String toServer=String.valueOf(object);

                                        ServerMessage serverMessage= NetWorkUtils.getInstance().create(toServer,"/delete_user");
                                        int code=serverMessage.getRespondCode();
                                        if(code==200)
                                        {
                                            String fromServer=(String)serverMessage.getFromServer();
                                            JSONObject obj=new JSONObject(fromServer);
                                            int o=obj.getInt("ownBooks");
                                            if(o==0) {
                                                Message message = new Message();
                                                message.obj = position;
                                                message.what = DELETE_SUCCESS;
                                                handler.sendMessage(message);
                                            }
                                            else
                                            {
                                                Message message = new Message();
                                                message.obj = position;
                                                message.what = DELETE_DENY;
                                                handler.sendMessage(message);
                                            }
                                        }
                                        else
                                        {
                                            Message message=new Message();
                                            message.what=DELETE_FAIL;
                                            handler.sendMessage(message);
                                        }
                                    }catch (JSONException e){e.printStackTrace();}
                                    catch (IOException e){e.printStackTrace();
                                        Message message=new Message();
                                        message.what=DELETE_FAIL;
                                        handler.sendMessage(message);}
                                }
                            }.start();

                        }
                    });
                    builder.create().show();

                }
            });


        return convertView;
    }
}
